package com.zyx.camunda.config.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @author zyx
 * @since 2023/9/21 10:08
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    private static final int DEFAULT_ORDER = 0;

    @Bean
    public UserHandlerInterceptor getUserHandlerInterceptor() {
        return new UserHandlerInterceptor();
    }

    @Bean
    public CamundaAuthInterceptor getCamundaAuthInterceptor() {
        return new CamundaAuthInterceptor();
    }

    List<String> pathExcludes = Arrays.asList(
        "/actuator/**",
        "/api/server/checkHealth",
        "/swagger-resources/**",
        "/webjars/**",
        "/v3/**",
        "/doc.html",
        "/swagger-ui.html",
        "/doc.html",
        "/error"
    );


    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 需要保证用户拦截器先执行，保证camunda拦截器可以获取到用户id
        registry.addInterceptor(getUserHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns(pathExcludes).order(DEFAULT_ORDER + 1);
        registry.addInterceptor(getCamundaAuthInterceptor()).addPathPatterns("/**").excludePathPatterns(pathExcludes).order(DEFAULT_ORDER + 2);
    }

    /**
     * 静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    }

}
